package com.ccit.integral.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ccit.common.exception.GymException;
import com.ccit.common.result.Result;
import com.ccit.common.utils.RedisUtils;
import com.ccit.common.utils.UploadUtil;
import com.ccit.integral.service.IntegralGoodsService;
import com.ccit.integral.service.IntegralRecordService;
import com.ccit.integral.service.impl.IntegralServiceImpl;
import com.ccit.model.Integral;
import com.ccit.model.IntegralGoods;
import com.ccit.model.IntegralRecord;
import com.ccit.model.vo.integral.IntrgralVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Api(tags = "积分管理")
@RestController
@RequestMapping("/integral")
public class IntegralController {
    @Autowired
    private IntegralServiceImpl integralService;
    @Autowired
    private IntegralGoodsService integralGoodsService;
    @Autowired
    private IntegralRecordService integralRecordService;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private UploadUtil uploadUtil;

    @ApiOperation(value = "获取所有手机号积分")
    @GetMapping("/getAllIntegral")
    public Result getAllPhoneIntegral() {
        String key = "AllIntegral";
        boolean hasKey = redisUtils.hasKey(key);
        List<Integral> integralList;
        if (hasKey) {
            integralList = (List<Integral>) redisUtils.get(key);
        } else {
            List<Integral> list = integralService.list();
            integralList = list;
            redisUtils.set(key, integralList);
        }

        return Result.ok(integralList);
    }

    @ApiOperation(value = "分页获取手机号积分")
    @GetMapping("/getPageIntegral/{current}/{size}")
    public Result getPhoneIntegral(@RequestParam(required = false) String phone,
                                   @PathVariable long current,
                                   @PathVariable long size) {
        Page<Integral> page;
        String key = "IntegralPage:" + current + ":" + size;
        if (phone != null) {
            key = "IntegralPage:" + phone + ":" + current + ":" + size;
        }
        boolean hasKey = redisUtils.hasKey(key);
        if (hasKey) {
            System.out.println("==============redis=====================");
            page = (Page<Integral>) redisUtils.get(key);
        } else {
            QueryWrapper<Integral> wrapper = new QueryWrapper<Integral>();
            if (phone != null) {
                wrapper.lambda()
                        .like(Integral::getPhone, phone);
            }
            Page<Integral> integralPage = new Page<>(current, size);
            page = integralService.page(integralPage, wrapper);
            redisUtils.set(key, page);
        }
        return Result.ok(page);
    }

    @ApiOperation(value = "获取手机号积分可换的积分商品")
    @GetMapping("/getPhoneIntegralExchange/{current}/{size}")
    public Result getPhoneIntegralExchange(@RequestParam(required = false) String phone,
                                           @PathVariable long current,
                                           @PathVariable long size) {
        Page<IntegralGoods> page;
        String key = "IntegralExchangePage:" + current + ":" + size;
        if (phone != null) {
            key = "IntegralExchangePage:" + phone + ":" + current + ":" + size;
        }
        boolean hasKey = redisUtils.hasKey(key);
        if (hasKey) {
            System.out.println("==============redis=====================");
            page = (Page<IntegralGoods>) redisUtils.get(key);

        } else {
            QueryWrapper<Integral> wrapper = new QueryWrapper<Integral>();
            QueryWrapper<IntegralGoods> queryWrapper = new QueryWrapper<IntegralGoods>();
            if (phone != null) {
                wrapper.lambda()
                        .eq(Integral::getPhone, phone);
                Integral integral = integralService.getOne(wrapper);
                if (integral == null) {
                    throw new GymException(202, "无此手机号积分");
                }
                queryWrapper.lambda()
                        .le(IntegralGoods::getExchange, integral.getIntegral())
                        .orderByDesc(IntegralGoods::getExchange);
            } else {
                queryWrapper.lambda()
                        .orderByDesc(IntegralGoods::getExchange);
            }
            Page<IntegralGoods> integralGoodsPage = new Page<>(current, size);
            page = integralGoodsService.page(integralGoodsPage, queryWrapper);
            redisUtils.set(key, page);
        }
        return Result.ok(page);
    }

    @ApiOperation(value = "积分兑换")
    @PutMapping("/IntegralExchange/{code}")
    public Result integralExchange(@PathVariable String code, @RequestBody IntrgralVo intrgralVo) {
        String key = "phone" + intrgralVo.getPhone() + "checkCode";
        System.out.println(key + "===============================");
        boolean hasKey = redisUtils.hasKey(key);
        System.out.println(redisUtils.get(key));
        System.out.println(code);
        if (hasKey) {
            if (redisUtils.get(key).toString().equals(code)) {
                QueryWrapper<Integral> wrapper = new QueryWrapper<Integral>();
                wrapper.lambda()
                        .eq(Integral::getPhone, intrgralVo.getPhone());
                Integral integral = integralService.getOne(wrapper);
                IntegralGoods integralGoods = integralGoodsService.getById(intrgralVo.getId());
                if (integral == null) {
                    throw new GymException(202, "无此手机号积分");
                }
                if (integralGoods == null) {
                    throw new GymException(202, "无此积分商品");
                }
                if (integralGoods.getExchange() * intrgralVo.getNum() > integral.getIntegral()) {
                    throw new GymException(202, "积分不够");
                }
                if (integralGoods.getStock() - intrgralVo.getNum() < 0) {
                    throw new GymException(202, "积分商品不足");
                }
                //修改积分
                integral.setIntegral(integral.getIntegral() - integralGoods.getExchange() * intrgralVo.getNum());
                boolean flag = integralService.updateById(integral);
                //修改库存
                integralGoods.setStock(integralGoods.getStock() - intrgralVo.getNum());
                boolean b = integralGoodsService.updateById(integralGoods);
                //存兑换记录
                IntegralRecord integralRecord = new IntegralRecord();
                integralRecord.setIntegralGoodsId(integralGoods.getId());
                integralRecord.setPhone(integral.getPhone());
                boolean save = integralRecordService.save(integralRecord);

                if (flag && b && save) {
                    redisUtils.deleteRedisKeys("IntegralPage");
                    redisUtils.deleteRedisKeys("AllIntegral");
                    redisUtils.deleteRedisKeys("IntegralExchangePage");
                    return Result.ok("兑换成功");
                } else {
                    throw new GymException(203, "积分修改或修改库存或存兑换记录出错");
                }
            } else throw new GymException(210, "验证码错误");
        } else throw new GymException(210, "验证码超时");

    }

    @ApiOperation(value = "修改积分")
    @PutMapping("/updateIntegral/{code}")
    public Result updateIntegral(@PathVariable String code, @RequestBody Integral integral) {
        String key = "phone" + integral.getPhone() + "checkCode";
        System.out.println(key + "===============================");
        boolean hasKey = redisUtils.hasKey(key);
        if (hasKey) {
            if (redisUtils.get(key).toString().equals(code)) {
                QueryWrapper<Integral> wrapper = new QueryWrapper<Integral>();
                wrapper.lambda()
                        .eq(Integral::getPhone, integral.getPhone());
                Integral one = integralService.getOne(wrapper);
                if (one == null) {
                    throw new GymException(202, "无此手机号");
                }
                boolean flag = integralService.updateById(integral);
                if (flag) {
                    redisUtils.deleteRedisKeys("IntegralPage");
                    redisUtils.deleteRedisKeys("AllIntegral");
                    redisUtils.deleteRedisKeys("IntegralExchangePage");
                    return Result.ok();
                } else {
                    return Result.fail().message("修改失败");
                }
            } else throw new GymException(210, "验证码错误");
        } else throw new GymException(210, "验证码超时");

    }

    @ApiOperation(value = "删除积分")
    @DeleteMapping("/deleteIntegral/{id}")
    public Result removeIntegral(@PathVariable("id") Integer id/*,@RequestPart String code*/) {
//        if (redisUtils.get("code").equals(code)){
        boolean byId = integralService.removeById(id);
        if (byId) {
            redisUtils.deleteRedisKeys("IntegralPage");
            redisUtils.deleteRedisKeys("AllIntegral");
            redisUtils.deleteRedisKeys("IntegralExchangePage");
            return Result.ok("删除成功");
        } else throw new GymException(202, "无此积分用户");
//        }else throw new GymException(210, "验证码错误");
    }

    @ApiOperation(value = "保存积分")
    @PostMapping("/saveIntegral")
    public Result uploadPicture(@RequestBody Integral integral) {
        boolean result = integralService.save(integral);
        if (result) {
            redisUtils.deleteRedisKeys("IntegralPage");
            redisUtils.deleteRedisKeys("AllIntegral");
            redisUtils.deleteRedisKeys("IntegralExchangePage");
            return Result.ok("添加成功");
        } else
            throw new GymException(203, "服务异常");
    }

    @ApiOperation(value = "修改积分")
    @PostMapping("/api/updateIntegral")
    public Boolean updateIntegral(@RequestBody Integral integral) {
        QueryWrapper<Integral> wrapper = new QueryWrapper<Integral>();
        wrapper.lambda()
                .eq(Integral::getPhone, integral.getPhone());
        System.out.println("integral=========================================>" + integral.toString());
        Integral one = integralService.getOne(wrapper);
        if (one == null) {
            boolean save = integralService.save(integral);
            if (!save) {
                throw new GymException(230, "添加积分出错");
            }
            redisUtils.deleteRedisKeys("IntegralPage");
            redisUtils.deleteRedisKeys("AllIntegral");
            redisUtils.deleteRedisKeys("IntegralExchangePage");
            return true;
        } else {
            one.setIntegral(one.getIntegral() + integral.getIntegral());
            boolean flag = integralService.updateById(one);
            System.out.println("=========================================>积分修改完成");
            if (flag) {
                redisUtils.deleteRedisKeys("IntegralPage");
                redisUtils.deleteRedisKeys("AllIntegral");
                redisUtils.deleteRedisKeys("IntegralExchangePage");
                return true;
            } else {
                return false;
            }
        }
    }
}
